package com.finalproject.endice9x9;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

//Load title fragment 
//Copy levels file from assets to sand box on first start
public class TitleFragment extends Fragment {

	//Copies file from assets to sand box
	private void copyFromAssetsToContext(String inFile, String outFile) throws IOException {
	    InputStream in = getActivity().getAssets().open(inFile);
	    OutputStream out = getActivity().openFileOutput(outFile,  Context.MODE_PRIVATE);

	    // Transfer bytes from in to out
	    byte[] buf = new byte[1024];
	    int len;
	    while ((len = in.read(buf)) > 0) {
	        out.write(buf, 0, len);
	    }
	    in.close();
	    out.close();
	}
	
	//Check if file exists in sand box
	private boolean fileExists(String inFile) {
		String[] files = getActivity().fileList();
	    for (String file : files) {
	        if (file.equals(inFile)) {
	            return true;
	        }
	    }
	    
	    return false;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(false);
		try {
			if(!fileExists("levels")) {
				copyFromAssetsToContext("levels", "levels");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//Inflate Title fragment layout and add onClick listeners to image buttons
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_title, parent, false);
		
		ImageView startImage = (ImageView)v.findViewById(R.id.startImage);
		startImage.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {				
				FragmentManager fm = getActivity().getFragmentManager();
				Fragment fragment = new GameFragment();
				fm.beginTransaction().replace(R.id.fragmentContainer, fragment).commit();
			}
		});

		ImageView infoImage = (ImageView)v.findViewById(R.id.infoImage);
		infoImage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				FragmentManager fm = getActivity().getFragmentManager();
				
				InfoFragment dialog = new InfoFragment(R.string.title_insrtuctions, 
						R.string.game_instructions);
				
				dialog.show(fm, InfoFragment.DIALOG_INFO);
			}
		});

		return v;
	}
}
